# -*- coding: utf-8 -*-
# !/usr/bin/env python
from rest_framework.views import APIView
from components.kubernetes.dao import get_k8s_cluster_hosts, get_config_file_text
from utils.K8S import K8sApi
from utils.views import Result, ReturnClass


class EnvClusterHost(APIView):
    def get(self, request):
        data = request.query_params
        return_data = []
        kubernetes_cluster_id = data['kubernetes_cluster_id']

        env_cluster_data = get_k8s_cluster_hosts(data['kubernetes_cluster_id'])

        kubernetes_cluster_sign_kubeconfig_r = get_config_file_text(kubernetes_cluster_id)

        # 假如有配置文件尝试使用配置文件查询K8S集群信息
        try:
            if ReturnClass.if_ok(kubernetes_cluster_sign_kubeconfig_r):
                kubernetes_cluster_sign_kubeconfig = ReturnClass.get_value(kubernetes_cluster_sign_kubeconfig_r)
                k8s_api = K8sApi(kubernetes_cluster_sign_kubeconfig)
                # get_top_nodes_items = k8s_api.get_top_nodes()
                for env_cluster_data_one in env_cluster_data:
                    if env_cluster_data_one['kubernetes_role']:
                        return_data.append(dict(env_cluster_data_one, **k8s_api.get_nodes_status(env_cluster_data_one['host_nick'])))
                    else:
                        return_data.append(env_cluster_data_one)
                    # for get_top_nodes_one  in get_top_nodes_items:
                    #     if get_top_nodes_one['metadata']['name'] == env_cluster_data_one['host_nick']:
                    #         cpu_n = int(get_top_nodes_one['usage']['cpu'][:-1])
                    #         memory_Ki = int(get_top_nodes_one['usage']['memory'][:-2])


            else:
                return_data = env_cluster_data
        except:
            return_data = env_cluster_data

        return Result.success_response(data=return_data, msg='查询成功')